package com.xie.wechat;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private String loginUrl = "http://10.23.34.211:3000/api/user/account/token/";
    private String test = "http://10.23.34.211:3000/test";
    private EditText edit_name, edit_psd;//用户名和密码的文本输入框
    private CheckBox checkBox;//是否保存密码的选择框
    private Button btn_login,btn_register;//登录按钮


    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public final static String BASE_URL="http://10.23.34.211:3000/";
    public final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)// 设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)// 设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)// 设置连接超时时间
            .build();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        istoken();
        initView(); // 初始化数据

    }

    private void istoken(){
        String token1 = "";
         //取 Token
        SharedPreferences  sharedPreferences = getSharedPreferences("mytoken", MODE_PRIVATE);
        Log.d("111111 MainActivity >>", "getAccess_token:" + sharedPreferences.getString("token", ""));
        token1 =  sharedPreferences.getString("token", "");
        if (!token1.isEmpty()){
            Intent intent=new Intent(LoginActivity.this,MainActivity.class);
            startActivity(intent);
        }
    }

    private void initView() {
        checkBox = (CheckBox) findViewById(R.id.logon_recall); // 记住密码选择框
        edit_name = (EditText) findViewById(R.id.name);
        edit_psd = (EditText) findViewById(R.id.password);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_register = (Button) findViewById(R.id.register);
        output(); // 刚进入就先取一次，看看当然状态

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_login.setBackground(getResources().getDrawable(R.drawable.btn_press_shape));//点击按钮后，重新设置背景颜色
                String username = edit_name.getText().toString().trim();
                String password = edit_psd.getText().toString().trim();

                // 输入框判空
                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "用户名/密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    login(username, password);
                }

            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_register.setBackground(getResources().getDrawable(R.drawable.btn_press_shape));//点击按钮后，重新设置背景颜色
                // Intent 去设置要跳转的页面
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                // 进行跳转
                startActivity(intent);

                finish();
            }
        });
    }

    private void login(String username, String password) {

        // 账号密码转为Json格式传给后台
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // 将要传的参数保存进Json对象
        JSONObject jsJson = new JSONObject();
        try {
            jsJson.put("username", username);
            jsJson.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("111111 jsJson ====", ":" + jsJson);
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsJson));
        Request request = new Request.Builder()
                .url(BASE_URL+"api/user/account/token/")

                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("111111 post 请求失败 ======", "e.getMessage()" + e.getMessage());
                Log.d("111111 post 请求失败 ======", "e.request()" + call.request());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功返回结果
                // 如果希望返回的是字符串

                final   String responseData =new String(response.body().string());
                // 如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
                InputStream responseStream = response.body().byteStream();
                // 注意，此时的线程不是ui线程，
                // 如果此时我们要用返回的数据进行ui更新，操作控件，就要使用相关方法

                Log.d("111111 post 请求成功 ===", "responseData >>" + responseData);
                Log.d("111111 post 请求成功 ===", "responseStream >>" + responseStream);



                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        LoginBean bean = new Gson().fromJson(responseData,  LoginBean.class);
                        String status = bean.getMsg().toString();
                        Log.d("111111post请求成功======", bean.getMsg().toString());
                        if (status.equals( "success" )) {
                        String token = bean.getToken();
                        Log.d("111111post请求成功======", token);
                        // 存Token
                        SharedPreferences sharedPreferences = getSharedPreferences("mytoken", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("token", token);
                        editor.commit();



                        input();

                        // Intent 去设置要跳转的页面
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        // 进行跳转
                        startActivity(intent);

                        finish();
                        }else{
                            Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }
        });

    }

    /**
     * 取出缓存的账号密码
     */
    private void output() {
        // 第一个参数是文件名，第二个参数是模式（不明白可以去补习一下SharedPreferences的知识）
        SharedPreferences shared = getSharedPreferences("mypassword", MODE_PRIVATE);
        // 第一个参数就是关键字，第二个参数为默认值，意思是说如果没找到值就用默认值代替
        String name1 = shared.getString("name", "");//同上，若没找到就让它为空""
        String psd1 = shared.getString("psd", "");
        boolean ischecked1 = shared.getBoolean("isChecked", false);
        edit_name.setText(name1);
        edit_psd.setText(psd1);
        checkBox.setChecked(ischecked1);
    }


    private void input() {

        // 第一个参数是文件名，第二个参数是模式（不明白可以去补习一下SharedPreferences的知识）
        SharedPreferences.Editor edit = getSharedPreferences("mypassword", MODE_PRIVATE).edit();
        // 判断选择框的状态   被选中isChecked或……
        if (checkBox.isChecked()) {
            edit.putString("name", edit_name.getText().toString());
            edit.putString("psd", edit_psd.getText().toString());
            edit.putBoolean("isChecked", true);
        } else {
            // edit.clear(); // 若选择全部清除就保留这行代码，注释以下三行
            edit.putString("name", edit_name.getText().toString());//只存用户名
            edit.putString("psd", "");
            edit.putBoolean("isChecked", false);
        }
        edit.commit();
    }
}
